package com.frejoys.app.controller;

import cn.hutool.core.util.StrUtil;
import com.frejoys.common.aop.Authority;
import com.frejoys.common.aop.Authorization;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.dto.common.upload.UploadPolicyDto;
import com.frejoys.common.enums.ESite;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.response.Result;
import com.frejoys.common.service.AliStorageService;
import com.frejoys.common.util.AppConfigUtil;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.service.ResourceLibraryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Tag(name = "上传", description = "上传")
@RestController
@RequiredArgsConstructor
@RequestMapping(CommonConstant.routePrefixApp)
 @Authorization(Authority.Private)
public class UploadController {

    private final AliStorageService aliStorageService;

    private final ResourceLibraryService resourceLibraryService;

    @Operation(summary = "获取服务端签名直传并设置上传回调签名")
    @PostMapping("/upload/policy")
    public Result uploadPolicy(@RequestBody @Validated UploadPolicyDto dto) {
        if (!ESite.getValues().contains(dto.getSite())) {
            throw new GeneralException(HttpStatus.uploadSiteNoExist);
        }

        Map<String, String> m = aliStorageService.getPolicy(dto.getSuffix());

        String fname = m.get(CommonConstant.fname);
        if (!StrUtil.isEmpty(fname)) {
            // 入库
            if (!resourceLibraryService.addInfo(RequestUtil.userId(), fname, dto.getSite())) {
                throw new GeneralException(HttpStatus.uploadPolicyFileFail);
            }
        }

        m.put(CommonConstant.fnameUrl, AppConfigUtil.getUrlPrefix(fname));

        return Result.success(m);
    }

}
